<template>
	<view>
		<view style="padding: 5px;" v-if="roleName=='宿管老师' || roleName=='维修管理员'">
			<uni-row>
				<uni-col :span="14">
					<uni-datetime-picker v-model="rq" type="date" disabled/>
				</uni-col>

				<uni-col :span="9" :offset="1">
					<button type="primary" style="height: 37px;line-height: 37px;" @click="submitHealth">提交</button>
				</uni-col>
			</uni-row>
		</view>

		<uni-section title="宿舍整体卫生情况" type="line">
			<uni-group style="display: flex; justify-content: space-around">
				<button class="clearBtn" :class="{'attBtnFontSlec':dorGrage === 1 }" @click="selectHygiene(1)">优秀</button>
				<button class="clearBtn" :class="{'attBtnFontSlec':dorGrage === 2 }" @click="selectHygiene(2)">良好</button>
				<button class="clearBtn" :class="{'attBtnFontSlec':dorGrage === 3 }" @click="selectHygiene(3)">差</button>
			</uni-group>
		</uni-section>

		<uni-section title="卫生检查项目" type="line">
			<uni-row v-for="(item,index) in dorHygieneDetailsList" :key="index">
				<view style="margin: 0 5px 10px 5px;height: 30px;">
					<uni-col :span="6">
						<view style="line-height: 30px;">
							{{item.dictLabel}}
						</view>
					</uni-col>
					<uni-col :span="6">
						<button @click="selectHygieneItem(item,1)"
							class="clearBtn" :class="{'attBtnFontSlec':item.grade === 1 }">优秀</button>
					</uni-col>
					<uni-col :span="6">
						<button @click="selectHygieneItem(item,2)"
							class="clearBtn" :class="{'attBtnFontSlec':item.grade === 2 }">良好</button>
					</uni-col>
					<uni-col :span="6">
						<button @click="selectHygieneItem(item,3)"
							class="clearBtn" :class="{'attBtnFontSlec':item.grade === 3 }">差</button>
					</uni-col>
				</view>
			</uni-row>
		</uni-section>

		<uni-section title="学生个人卫生情况" type="line">
			<uni-row v-for="(item,index) in dorStudentHygieneDetailsList" :key="index">
				<view style="margin: 0 5px 10px 5px;height: 30px;">
					<uni-col :span="6">
						<view style="line-height: 30px;">
							{{item.studentName}}
						</view>
					</uni-col>
					<uni-col :span="6">
						<button @click="selectStuHygiene(item,1)"
							class="clearBtn" :class="{'attBtnFontSlec':item.grade === 1 }">优秀</button>
					</uni-col>
					<uni-col :span="6">
						<button @click="selectStuHygiene(item,2)"
							class="clearBtn" :class="{'attBtnFontSlec':item.grade === 2 }">良好</button>
					</uni-col>
					<uni-col :span="6">
						<button @click="selectStuHygiene(item,3)"
							class="clearBtn" :class="{'attBtnFontSlec':item.grade === 3 }">差</button>
					</uni-col>
				</view>
			</uni-row>
		</uni-section>

		<uni-section title="卫生照片" type="line">
			<uni-file-picker limit="9" v-model="fileList" @select="selectPhoto" @delete="delPhoto" :readonly="roleName!=='宿管老师' && roleName!=='维修管理员'"/>
		</uni-section>

	</view>
</template>

<script>
	import teachClass from "@/api/modules/teachClass.js"
	import {
		parseTime
	} from "@/utils/date.js"
	import managementTeacher from '@/api/modules/managementTeacher.js'

	export default {
		name: 'dorManDetail',
		onLoad(options) {
			uni.showLoading({
				mask: true,
				title: '加载中'
			});

			this.optDormitoryId = options.dormitoryId;
			this.optDormitoryNo = options.dormitoryNo;
			this.optCheckTimeSpan = options.checkTimeSpan;
			if(options.rq) {
				this.rq = options.rq;
			}

			//获取宿舍卫生检查项
			teachClass.getDictByType("sd_hygiene_classify").then(res => {
				this.dictDorHygieneCheckItem = res.data
				//宿舍卫生检查项
				this.dorHygieneDetailsList = res.data;
        if(this.optCheckTimeSpan !== '0') { //日常卫生不需要铁皮柜门卫生，空床铺无杂物
          console.log("移除两项")
          this.dictDorHygieneCheckItem = this.dictDorHygieneCheckItem.filter(item => item.dictValue !== '13')
          this.dictDorHygieneCheckItem = this.dictDorHygieneCheckItem.filter(item => item.dictValue !== '14' )
          this.dorHygieneDetailsList = this.dorHygieneDetailsList.filter(item => item.dictValue !== '13')
          this.dorHygieneDetailsList = this.dorHygieneDetailsList.filter(item => item.dictValue !== '14' )
        }

				//获取宿舍学生列表
				managementTeacher.getStudentByDormitoryId(this.optDormitoryId).then (res=> {
					console.log('宿舍学生列表',res);
					if(res.data === '当前宿舍无学生!!!') {
						this.dorStudentList = [];
					}else {
						this.dorStudentList=res.data;
						//学生卫生检查项
						this.dorStudentHygieneDetailsList = res.data;
					}

					//获取宿舍卫生详情
					this.getDormitoryHygieneDetails();
				})
			});
		},
		data() {
			return {
				optDormitoryId : '',// 宿舍id
				optDormitoryNo : '',// 宿舍号
				optCheckTimeSpan : 0, //检查时间段
				rq: parseTime(Date.now()).slice(0, 10), //检查日期

				userName : uni.getStorageSync("userName"),
				roleName : uni.getStorageSync("roleName"),

				dictDorHygieneCheckItem: [], //宿舍卫生检查项字典
				dorStudentList : [], //宿舍学生列表

				dormitoryHygieneId: '', //宿舍卫生表id
				dorGrage: '', //宿舍整体卫生评级
				dorHygieneDetailsList: [], //宿舍卫生详情
				dorStudentHygieneDetailsList :[], //宿舍学生卫生详情

				differ: 0, //宿舍卫生项差个数
				good: 0, //宿舍卫生项良好个数
				great: 0, //宿舍卫生项优秀个数

				fileList: [], //图片结果list
				delPhotoIds: [], //删除数据库图片的id
			}
		},
		methods: {
			//查询宿舍卫生检查情况
			getDormitoryHygieneDetails() {
				this.$api.dormitory.getDormitoryHygieneDetails(this.optDormitoryId,this.optCheckTimeSpan,this.rq).then (res=> {
					uni.hideLoading();
					console.log("宿舍今日卫生情况：",res.data);
					//今日未检查
					if(res.data === null) {
						return ;
					}

					//今日已检查
					this.dormitoryHygieneId=res.data.dormitoryHygieneId; //宿舍卫生表id
					this.dorGrage=res.data.grade; //宿舍评级赋值

					//宿舍卫生详情赋值
					// this.dorHygieneDetailsList = res.data.dormitoryHygieneItemList
					// this.dorHygieneDetailsList.forEach(item => {
					// 	this.dictDorHygieneCheckItem.forEach(e => {
					// 		if (item.checkItem === parseInt(e.dictValue, 10)) {
					// 			item.dictLabel = e.dictLabel
					// 		}
					// 	})
					// })

					let tempDorHygieneDetailsList = res.data.dormitoryHygieneItemList

					this.dictDorHygieneCheckItem.forEach(e => {
						tempDorHygieneDetailsList.forEach(item => {
						   if (item.checkItem === parseInt(e.dictValue, 10)) {
							   e.grade = item.grade
							   e.checkItem = item.checkItem
							   e.dormitoryHygieneId = item.dormitoryHygieneId
							   e.id = item.id
							}
						})
					})
					this.dorHygieneDetailsList = this.dictDorHygieneCheckItem


					//照片赋值
					this.fileList = res.data.photos.map(item => ({
						url: item.photo,
						extname: '',
						name: item.id
					}));


					//宿舍学生卫生详情赋值
					let studentHygienes = res.data.dormitoryHygieneStudentList;
					if(studentHygienes !== null) {
						this.dorStudentHygieneDetailsList = studentHygienes;
						this.dorStudentHygieneDetailsList.forEach(item => {
							this.dorStudentList.forEach(e => {
								if(item.studentId === e.id) {
									item.studentName = e.studentName
								}
							})
						})
					}
				})
			},
			//宿舍整体卫生项选择
			selectHygiene(index) {
				this.dorGrage = index;
				this.dorHygieneDetailsList.forEach(item => {
					item.grade = index;
				});
				this.$forceUpdate();
			},
			//宿舍卫生项选择
			selectHygieneItem(item, index) {
				item.grade = index;

				this.differ = 0
				this.good = 0
				this.great = 0
				this.dorHygieneDetailsList.forEach(item => {
					if (item.grade === 3) {
						this.differ++
					} else if (item.grade === 2) {
						this.good++
					} else if (item.grade === 1) {
						this.great++
					}
				});

				if (this.differ > 0) {
					this.dorGrage = 3
				} else if (this.good > 0) {
					this.dorGrage = 2
				} else {
					this.dorGrage = 1
				}
			},
			//学生卫生项选择
			selectStuHygiene(item, index) {
				item.grade = index;
				this.$forceUpdate();
			},
			//卫生检查提交
			submitHealth () {
				uni.showLoading({
					mask: true,
					title: '提交中'
				});
				console.log(this.optCheckTimeSpan)
				if(this.optCheckTimeSpan == 0) {
						// 检查是否有未选择的项
					if (this.dorHygieneDetailsList.some(item => !item.grade)) {
						uni.showToast({
						  title: "请选择所有卫生检查项目",
						  icon: "none"
						});
						return;
					}
				}

				let resultHygieneStudentList = this.dorStudentHygieneDetailsList.filter(item => item.grade != null)
					.map(item => ({
						studentId: item.studentId ? item.studentId : item.id,
						grade: item.grade,
					}));
				if( resultHygieneStudentList.length !== 0 && resultHygieneStudentList.length !== this.dorStudentHygieneDetailsList.length) {
					uni.showToast({
					  title: "请检查所有学生",
					  icon: "none"
					});
					return;
				}

				let resultHygieneItemList = [
					...this.dorHygieneDetailsList.map(item => {
					  let obj = {};
					  if (item.dictValue) {
					    obj.checkItem = item.dictValue;
					  } else if (item.checkItem) {
					    obj.checkItem = item.checkItem;
					  }
					  obj.grade = item.grade;
					  return obj;
					})
				];

				let photoList = this.fileList
				    .filter(obj => obj.name === '')
				    .map(obj => obj.url);

				if(this.dorGrage == null || this.dorGrage === '') {
					uni.showToast({
					  title: "请至少检查一项卫生检查项目!",
					  icon: "none"
					});
					return;
				}
				//提交参数
				let submitHygieneInfo = {
					dormitoryHygieneId : this.dormitoryHygieneId,
					dormitoryId : this.optDormitoryId,
					checkTimeSpan : this.optCheckTimeSpan,
					checkUser　: this.userName,
					grade :　this.dorGrage,
					dormitoryHygieneItemList : resultHygieneItemList,
					dormitoryHygieneStudentList : resultHygieneStudentList,
					photos : photoList,
					delPhotoIds : this.delPhotoIds,
				}

				//提交成功后跳转回页面
				this.$api.dormitory.submitHygiene(submitHygieneInfo).then(res=> {
					uni.hideLoading();
					uni.navigateBack({
						delta: 1
					});
					//消息推送
					if(this.dorGrage === 3) {
						this.$api.dormitory.pushDorHygieneInfo(this.optDormitoryId,this.dorGrage,this.optCheckTimeSpan,this.rq);
					}
				});
			},
			selectPhoto(e) {
			   console.log('选择图片：', e)
			   e.tempFiles.forEach(tempFile => {
				   uni.uploadFile({
				     url: uni.url + 'dormitory/hygiene/uploadHygienePhoto',
				     filePath: tempFile.url,
				     // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
				     name: 'file',
				     header: {
				       'Authorization': "Bearer " + uni.getStorageSync("token")
				     },
				     // 成功函数
				     success: (res) => {
						console.log('上传成功', res.data);
						var obj = JSON.parse(res.data);
						this.fileList.push({
							url: obj.data,
							extname: '',
							name: ''
						})
						console.log(this.fileList);
				     },
				     // 失败提示用户重新上传
				     fail: error => {
				       console.log('上传失败', error);
				     }
				    })
			   })
			 },
			 delPhoto(e) {
				 console.log("删除图片",e);
				 if(e.tempFile.name !== '') {
					 this.delPhotoIds.push(e.tempFile.name);
				 }
			 }
		}
	}
</script>

<style>
	.indexContent {
		height: 100vh;
	}

	textarea {
		border-radius: 10rpx;
		border: 1rpx solid #e9e9e9;
		height: 150rpx;
		width: 95%;

		margin: 0 auto;
		margin-top: 20rpx;
	}

	.attBtnFontSlec {
		background-color: #007AFF;
		color: white !important;
	}

	.clearBtn {
		width: 160rpx;
		border-radius: 10rpx;
		font-size: 32rpx;
		color: #0000FF;
		text-align: center;
		border: 1px solid #0000FF;
		line-height: 60rpx !important;
		height: 30px;
	}

	.attLine {
		width: 640rpx;
		height: 2rpx;
		background: #C0C0C0;
		position: relative;
		bottom: -20rpx;
		left: 10rpx;
	}



	.timePos {
		position: relative;
		top: 0px;
		right: 0px;
		background: white;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		font-size: 38rpx;
	}
</style>
